﻿using Microsoft.OpenApi.Models;
using Nucleic.Web.Filters;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace Nucleic.Web.Swagger
{
    public class AuthResponsesOperationFilter : IOperationFilter
    {
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            var authAttributes = context.MethodInfo.DeclaringType.GetCustomAttributes(true)
            .Union(context.MethodInfo.GetCustomAttributes(true))
            .OfType<CheckPermissionAttribute>();
            if (authAttributes.Any())
            {
                var scheme = new OpenApiSecurityScheme()
                {
                    Description = "header token",
                    Reference = new OpenApiReference
                    {
                        Type = ReferenceType.SecurityScheme,
                        Id = "token"
                    },
                    Scheme = "",
                    Name = "token",// 默认参数名称
                    In = ParameterLocation.Header,//默认存放Authorization信息的位置（请求头）
                    Type = SecuritySchemeType.ApiKey,
                };
               
                var requirement = new OpenApiSecurityRequirement();
                requirement[scheme] = new List<string>();
                operation.Security.Add(requirement);
            }
        }
    }
}
